import React from 'react';
import PropTypes from 'prop-types';
import {injectIntl,} from 'react-intl';
import {get,} from 'lodash';

import {Accordion, AccordionSet, FilterAccordionHeader,} from '@folio/stripes/components';

import {CheckboxFilter, DateRangeFilter} from '@folio/stripes/smart-components';

import {DATE_FORMAT, statusFilter, storageFilter} from '../../constants';
import {makeDateRangeFilterString, retrieveDatesFromDateRangeFilterString} from '../../utils';


class Filters extends React.Component {
    static propTypes = {
      activeFilters: PropTypes.object,
      intl: PropTypes.shape({
        formatMessage: PropTypes.func.isRequired,
      }).isRequired,
      resources: PropTypes.object.isRequired,
      onChangeHandlers: PropTypes.object.isRequired,
      resultOffset: PropTypes.shape({
        replace: PropTypes.func.isRequired,
      }),
    };

    static defaultProps = {
      activeFilters: {},
    }

    getCheckboxOptions = (items) => {
      return items.map(({ label, value }) => ({
        label, value,
      }));
    };

    /**
     * Helper for formatting resource records information for <MultiSelection> component
     *
     * @param {String} type - resource type
     * @param {String} labelKey - propery of resource record that will serve as an option label
     * @param {String} valueKey - property of resource record that will serve as an option value.
     * Will be passed to search request query parameter string as a value.
     * @returns {Array} - an array of data options for <MultiSelection> component.
     */
    getValuesFromResources = (type, labelKey, valueKey) => {
      const items = get(this.props.resources, `${type}.records`, [])
        .map(item => ({ label: item[labelKey], value: item[valueKey] }));
      return items.sort((a, b) => a.label.localeCompare((b.label)));
    };

    handleFilterChange = (filter) => {
      const {
        activeFilters,
        onChangeHandlers,
        resultOffset,
      } = this.props;

      if (resultOffset) {
        resultOffset.replace(0);
      }

      onChangeHandlers.state({
        ...activeFilters,
        [filter.name]: filter.values
      });
    };

    render() {
      const {
        activeFilters: {
          status = [],
          storage = [],
          inDate = [],
        },
        onChangeHandlers: { clearGroup },
        intl: { formatMessage },
      } = this.props;

      return (
        <AccordionSet>
          <Accordion
            displayClearButton
            id="bookInSgorage-filter-accordion-status"
            header={FilterAccordionHeader}
            label="状态"
            separator={false}
            onClearFilter={() => clearGroup('status')}
          >
            <CheckboxFilter
              dataOptions={this.getCheckboxOptions(statusFilter)}
              name="status"
              selectedValues={status}
              onChange={this.handleFilterChange}
            />
          </Accordion>
          <Accordion
            displayClearButton
            id="bookInSgorage-filter-accordion-storage"
            header={FilterAccordionHeader}
            label="入藏地点"
            separator={false}
            onClearFilter={() => clearGroup('storage')}
          >
            <CheckboxFilter
              dataOptions={this.getCheckboxOptions(storageFilter)}
              name="storage"
              selectedValues={storage}
              onChange={this.handleFilterChange}
            />
          </Accordion>
          <Accordion
            label="入库日期"
            id="inDate"
            name="inDate"
            closedByDefault
            header={FilterAccordionHeader}
            displayClearButton={inDate.length > 0}
            onClearFilter={() => clearGroup('inDate')}
          >
            <DateRangeFilter
              name="inDate"
              dateFormat={DATE_FORMAT}
              selectedValues={retrieveDatesFromDateRangeFilterString(inDate[0])}
              onChange={this.handleFilterChange}
              makeFilterString={makeDateRangeFilterString}
            />
          </Accordion>
        </AccordionSet>
      );
    }
}

export default injectIntl(Filters);
